import React, { useState, useEffect } from "react";
import { View, FlatList } from "react-native";
import { useTheme } from "@/contexts/ThemeContext";
import { Ionicons } from "@expo/vector-icons";
import AlertService from "@/components/Global/Alert/service";

// 导入全局组件
import Loading from "@/components/Global/Loading";
import EmptyState from "@/components/Global/EmptyState";

// 导入类型和辅助函数
import { GroupNotificationItem, NotificationAction } from "./types";
import { mockNotifications } from "./mockData";
import { createStyles } from "./styles";

// 导入组件
import NotificationItem from "./components/NotificationItem";

const GroupNotification = () => {
  const { colors } = useTheme();
  const styles = createStyles();
  const [notifications, setNotifications] = useState<GroupNotificationItem[]>(
    []
  );
  const [loading, setLoading] = useState<boolean>(true);
  const [refreshing, setRefreshing] = useState<boolean>(false);

  // 模拟加载通知数据
  useEffect(() => {
    const fetchNotifications = async () => {
      try {
        // 这里应该是从API获取数据
        // 暂时使用模拟数据
        setTimeout(() => {
          setNotifications(mockNotifications);
          setLoading(false);
        }, 1000);
      } catch (error) {
        console.error("获取群通知失败:", error);
        AlertService.showAlert("error", "获取通知失败，请稍后重试");
        setLoading(false);
      }
    };

    fetchNotifications();
  }, []);

  // 模拟刷新通知数据
  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      // 这里应该是从API获取最新数据
      setTimeout(() => {
        setNotifications(mockNotifications);
        setRefreshing(false);
      }, 1000);
    } catch (error) {
      console.error("刷新通知失败:", error);
      AlertService.showAlert("error", "刷新失败，请稍后重试");
      setRefreshing(false);
    }
  };

  // 处理通知操作
  const handleNotificationAction = (
    notificationId: string,
    action: NotificationAction
  ) => {
    const notification = notifications.find((n) => n.id === notificationId);
    if (!notification) return;

    // 根据通知类型和操作执行不同的逻辑
    switch (notification.type) {
      case "invitation":
        if (action === "accept") {
          // 接受群邀请的逻辑
          AlertService.showAlert(
            "success",
            `已加入群聊 ${notification.groupName}`
          );
        } else {
          // 拒绝群邀请的逻辑
          AlertService.showAlert(
            "info",
            `已拒绝加入 ${notification.groupName}`
          );
        }
        break;
      case "join_request":
        if (action === "accept") {
          // 同意加入请求的逻辑
          AlertService.showAlert(
            "success",
            `已同意 ${notification.senderName} 加入群聊`
          );
        } else {
          // 拒绝加入请求的逻辑
          AlertService.showAlert(
            "info",
            `已拒绝 ${notification.senderName} 的加入请求`
          );
        }
        break;
      case "dissolution":
      case "role_promoted":
      case "role_demoted":
        // 确认已读通知
        AlertService.showAlert("info", "已标记为已读");
        break;
    }

    // 更新通知状态为"已处理"，并记录操作结果
    setNotifications(
      notifications.map((n) =>
        n.id === notificationId
          ? { ...n, status: "processed", actionResult: action }
          : n
      )
    );
  };

  // 渲染分隔线
  const renderSeparator = () => <View style={{ height: 8 }} />;

  // 自定义空状态图标
  const emptyIcon = (
    <Ionicons
      name="notifications-off-outline"
      size={64}
      color={colors.text.secondary}
    />
  );

  return (
    <View
      style={[styles.container, { backgroundColor: colors.backgroundLight }]}
    >
      <Loading visible={loading} />
      {!loading && (
        <FlatList
          data={notifications}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => (
            <NotificationItem item={item} onAction={handleNotificationAction} />
          )}
          ItemSeparatorComponent={renderSeparator}
          contentContainerStyle={{
            paddingVertical: 8,
            flexGrow: notifications.length === 0 ? 1 : undefined,
          }}
          ListEmptyComponent={
            <EmptyState
              icon={emptyIcon}
              title="暂无群聊通知"
              subtitle="当有新的群聊通知时会显示在这里"
            />
          }
          refreshing={refreshing}
          onRefresh={handleRefresh}
          showsVerticalScrollIndicator={false}
        />
      )}
    </View>
  );
};

export default GroupNotification;
